//
//  HDIdentificationViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/4/7.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import CryptoSwift
import SVProgressHUD


enum enterType {
    static let enterNum = "请输入证件号"
    static let enterName = "请输入姓名"
}

class HDIdentificationViewController: UIViewController,UITextFieldDelegate
{
    
    var regStr:PYPReg?
    var entertype:enterType?
    let idContentView = HDIdContentView()
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0xf8f8f8)
        title = "身份验证"
        setupViews()
    }
    
    //MARK:文本框的高度
    override func viewWillAppear(_ animated: Bool) {
        setupNotification()
    }
    override func viewWillDisappear(_ animated: Bool) {
        removeNotification()
    }
    func removeNotification() {
        NotificationCenter.default.removeObserver(self)
    }
    func setupNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(HDIdentificationViewController.keyBoardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(HDIdentificationViewController.keyBoardWillhide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    func keyBoardWillShow() {
        UIView.animate(withDuration: 0.25, animations: {
            self.idContentView.snp.updateConstraints { (make) in
                make.top.equalTo(-200)
            }
            self.view.layoutIfNeeded()
        }) 
        
    }
    func keyBoardWillhide() {
        UIView.animate(withDuration: 0.25, animations: {
            self.idContentView.snp.updateConstraints { (make) in
                make.top.equalTo(self.view)
            }
            self.view.layoutIfNeeded()
        }) 
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        idContentView.idTypeTextField.textField.resignFirstResponder()
        idContentView.nameTextField.textField.resignFirstResponder()
    }
    
    //MARK: setUpView
    func setupViews() {
        view.addSubview(idContentView)
        idContentView.delegate = self
        idContentView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
}

// MARK: - HDIdContentViewDelegate
extension HDIdentificationViewController : HDIdContentViewDelegate {
    
    func didSelectIdent(_ typeID: String,typeInfo:String) {
        
        regStr?.critcode = idContentView.idTypeTextField.textField.text
        regStr?.name = idContentView.nameTextField.textField.text
        regStr?.crittype = typeID
        regStr?.crittype_info = typeInfo
        if regStr?.critcode == nil || regStr?.critcode == "" {
            enterNumber()
            return
        }
        
        if regStr?.name == nil || regStr?.name == "" {
            enterName()
            return
        }
        
        SVProgressHUD.showDisableLoading(nil)
        
        HDApiManagerHandler.requestReg(regStr!, success: {[unowned self] (respon) in
            
            print("-----succ---------\(respon)")
            
            if respon["status"]?.int32Value == 1 {
                SVProgressHUD.dismiss()
                let regRespon = respon["data"] as! [String:AnyObject]
                
                let regR = PYPRegRespond.parse(regRespon as NSDictionary)
                HDAccountHandler.saveUserPhone((self.regStr?.phone)!)
                HDAccountHandler.saveUserIntType((regR.user_type?.intValue)!)
                // 登录
                self.registerSuccToLogin()
                
            }else if respon["status"]?.int32Value == 2 {
                SVProgressHUD.dismiss()
                self.idContentView.bottomPromptView.text = "您填写的身份证未满18岁,请填写监护人的信息进行注册"
                return
            }else {
                let msg = respon["msg"] as! String
                SVProgressHUD.showError(msg)
                return
            }
            
        }) { (error) in
            SVProgressHUD.dismiss()
            print(error)
            return
        }
    }
    
    func registerSuccToLogin () {
        
        let ckAuthCode = PYPLogin(phone: self.regStr!.phone, ptxt: self.regStr!.ptxt, did: AppConstant.did, login_type:"1")
        HDApiManagerHandler.requestLogin(ckAuthCode, success: { [unowned self](dict) in
            print(dict)
            if dict["status"]?.int32Value == 1 {
                
                let regRespon = dict["data"] as! [String:AnyObject]
                let regR = PYPRegRespond.parse(regRespon as NSDictionary)
                HDAccountHandler.saveUserToken(regR.token!)
                HDAccountHandler.saveUserIntType((regR.user_type?.intValue)!)
                
                NotificationCenter.default.post(name: Notification.Name(rawValue: HDUserNotification.userlogin), object: nil)

                self.navigationController?.popToRootViewController(animated: true)
                let a = UserDefaults.standard.bool(forKey: "GuideRegister")
                print(a)
                if a {
                    let vc = ViewController();
                    UIApplication.shared.keyWindow?.rootViewController = vc;
                    self.dismiss(animated: true, completion: nil)
                    
                    UserDefaults.standard.set(false, forKey: "GuideRegister")
                }else{
                
                    self.navigationController?.popToRootViewController(animated: true)
                }
            }else {
                let msg = dict["msg"] as! String
                SVProgressHUD.showError(msg)
            }
        }) { (error) in
            
        }
    }
    
    //MARK:提示输入证件号和姓名
    func enterNumber() {
        SVProgressHUD.showError(enterType.enterNum)
    }
    func enterName() {
        SVProgressHUD.showError(enterType.enterName)
    }
}
